/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.remote;

import com.googlecode.actorom.Actor;
import com.googlecode.actorom.Address;
import com.googlecode.actorom.CompletableFutureResult;
import com.googlecode.actorom.FutureResult;
import com.googlecode.actorom.impl.core.CoreFutureResult;
import com.googlecode.actorom.remote.RemoteAddress;
import com.googlecode.actorom.impl.remote.channel.protocol.Host;
import com.googlecode.actorom.impl.remote.channel.MessageChannelConnector;
import com.googlecode.actorom.impl.remote.channel.protocol.CommandAck;
import com.googlecode.actorom.impl.remote.channel.protocol.CommandHeader;
import com.googlecode.actorom.impl.remote.channel.protocol.IsActiveCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.LinkCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.SendCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.SendWithFutureCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.UnlinkCommand;
import com.googlecode.actorom.impl.remote.channel.protocol.support.ProtocolUtils;
import com.googlecode.actorom.support.ActorExecutionException;
import com.googlecode.actorom.support.ActorInvocationException;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import net.jcip.annotations.ThreadSafe;
import org.apache.commons.collections.map.ReferenceMap;

/**
 * @author Sergio Bossa
 */
// TODO: Pool MessageChannelConnector instances?
@ThreadSafe
public class RemoteActorProxy implements Actor {

    private final Host sender;
    private final Host receiver;
    private final RemoteAddress address;
    private final Map futures;

    public RemoteActorProxy(Host sender, Host receiver, RemoteAddress address) {
        this.sender = sender;
        this.receiver = receiver;
        this.address = address;
        futures = Collections.synchronizedMap(new ReferenceMap(ReferenceMap.HARD, ReferenceMap.WEAK));
    }

    public void send(Object message) {
        MessageChannelConnector channelConnector = new MessageChannelConnector(receiver.getHost(), receiver.getPort());
        try {
            channelConnector.connect();
            if (isActiveActor(channelConnector)) {
                String id = ProtocolUtils.generateCommandId();
                CommandHeader header = new CommandHeader(sender, receiver, id, null);
                CommandAck ack = channelConnector.sendSync(new SendCommand(header, address, message));
                if (!ack.isAcknowledged()) {
                    throw new ActorInvocationException("Error while sending message to remote actor: " + address);
                }
            } else {
                throw new ActorInvocationException("Error while sending message to remote actor: " + address);
            }
        } catch (IOException ex) {
            throw new ActorInvocationException(ex.getMessage(), ex);
        } finally {
            channelConnector.disconnect();
        }
    }

    public FutureResult send(Object message, long timeout, TimeUnit unit) {
        MessageChannelConnector channelConnector = new MessageChannelConnector(receiver.getHost(), receiver.getPort());
        try {
            channelConnector.connect();
            if (isActiveActor(channelConnector)) {
                String id = ProtocolUtils.generateCommandId();
                CompletableFutureResult future = new CoreFutureResult(unit.toNanos(timeout));
                futures.put(id, future);
                CommandHeader header = new CommandHeader(sender, receiver, id, null);
                CommandAck ack = channelConnector.sendSync(new SendWithFutureCommand(header, address, message, unit.toNanos(timeout)));
                if (ack.isAcknowledged()) {
                    return future;
                } else {
                    futures.remove(id);
                    throw new ActorInvocationException("Error while sending message to remote actor: " + address);
                }
            } else {
                throw new ActorInvocationException("Error while sending message to remote actor: " + address);
            }
        } catch (IOException ex) {
            throw new ActorInvocationException(ex.getMessage(), ex);
        } finally {
            channelConnector.disconnect();
        }
    }

    public void link(Actor actor) {
        MessageChannelConnector channelConnector = new MessageChannelConnector(receiver.getHost(), receiver.getPort());
        try {
            channelConnector.connect();
            if (isActiveActor(channelConnector)) {
                String id = ProtocolUtils.generateCommandId();
                CommandHeader header = new CommandHeader(sender, receiver, id, null);
                CommandAck ack = channelConnector.sendSync(new LinkCommand(header, address, (RemoteAddress) actor.getAddress()));
                if (!ack.isAcknowledged()) {
                    throw new ActorInvocationException("Error while linking from remote actor: " + address);
                }
            } else {
                throw new ActorInvocationException("Error while linking from remote actor: " + address);
            }
        } catch (IOException ex) {
            throw new ActorInvocationException(ex.getMessage(), ex);
        } finally {
            channelConnector.disconnect();
        }
    }

    public void unlink(Actor actor) {
        MessageChannelConnector channelConnector = new MessageChannelConnector(receiver.getHost(), receiver.getPort());
        try {
            channelConnector.connect();
            if (isActiveActor(channelConnector)) {
                String id = ProtocolUtils.generateCommandId();
                CommandHeader header = new CommandHeader(sender, receiver, id, null);
                CommandAck ack = channelConnector.sendSync(new UnlinkCommand(header, address, (RemoteAddress) actor.getAddress()));
                if (!ack.isAcknowledged()) {
                    throw new ActorInvocationException("Error while unlinking from remote actor: " + address);
                }
            } else {
                throw new ActorInvocationException("Error while unlinking from remote actor: " + address);
            }
        } catch (IOException ex) {
            throw new ActorInvocationException(ex.getMessage(), ex);
        } finally {
            channelConnector.disconnect();
        }
    }

    public boolean isActive() {
        MessageChannelConnector channelConnector = new MessageChannelConnector(receiver.getHost(), receiver.getPort());
        try {
            channelConnector.connect();
            return isActiveActor(channelConnector);
        } catch (IOException ex) {
            throw new ActorInvocationException(ex.getMessage(), ex);
        } finally {
            channelConnector.disconnect();
        }
    }

    public Address getAddress() {
        return address;
    }

    public void completeFuture(String id, Object result, ActorExecutionException exception) {
        CompletableFutureResult future = (CompletableFutureResult) futures.remove(id);
        if (future != null) {
            if (exception != null) {
                future.completeWithException(exception);
            } else {
                future.completeWithResult(result);
            }
        }
    }

    private boolean isActiveActor(MessageChannelConnector channelConnector) {
        String id = ProtocolUtils.generateCommandId();
        CommandHeader header = new CommandHeader(sender, receiver, id, null);
        CommandAck ack = channelConnector.sendSync(new IsActiveCommand(header, address));
        return ack.isAcknowledged();
    }
}
